#include "logindialog.h"
#include "qevent.h"
#include "ui_logindialog.h"
#include "registerdialog.h"
#include"httpmgr.h"
#include<QPushButton>
#include <usermgr.h>

LogInDialog::LogInDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LogInDialog)
{
    ui->setupUi(this);
    ui->user_edit->selectAll();
    ui->user_edit->setFocus();
    parentWindow = qobject_cast<MainWindow*>(this->parent());

    initHandlers();
    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_login_mod_finish, this, &LogInDialog::slot_login_mod_finish);
}

LogInDialog::~LogInDialog()
{
    delete ui;
}

void LogInDialog::showTip(const QString &test, bool isOk)
{
    if(isOk){
        ui->Ltip->setProperty("state", "normal");
        repolish(ui->Ltip);
    }else{
        ui->Ltip->setProperty("state", "err");
        repolish(ui->Ltip);
    }
    ui->Ltip->setText(test);
}

void LogInDialog::initHandlers()
{
    //登录回包逻辑
    _handlers.insert(std::make_pair(ReqId::ID_LOGIN_USER, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(static_cast<ErrorCodes>(error) != ErrorCodes::SUCCESS){
            showTip(tr("参数错误"),false);
            return;
        }

        _uid = jsonObj["user_id"].toInt();
        _token = jsonObj["token"].toString();

        ServerInfo si;
        si.user = jsonObj["username"].toString();
        si.Uid = _uid;
        si.Host = jsonObj["host"].toString();
        si.Port = QString::number(jsonObj["port"].toInt());
        si.Token = _token;

        UserMgr::GetInstance()->SetUid(_uid);

        qDebug()<< "user is " << si.user << "通过网关服务器";
        emit sig_logIn_tcp(si);
    }));
}

void LogInDialog::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        whereIsMouse = event->pos(); // 获取鼠标点击的坐标
    }
    QDialog::mousePressEvent(event);
}

void LogInDialog::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) // 如果鼠标左键被按下
    {
        //当在按钮之类需要鼠标操作的地方不进行触发(防误触)
        if (ui->pushButton->underMouse()||ui->pass_edit->underMouse()||ui->logInBtn->underMouse() || ui->user_edit->underMouse() || ui->registerBtn->underMouse())
        {
            QDialog::mouseMoveEvent(event);
            return;
        }
        parentWindow->move(QWidget::mapToGlobal(event->pos()-whereIsMouse));//移动
    }
    QDialog::mouseMoveEvent(event);
}

void LogInDialog::on_registerBtn_clicked()
{
    if (r != nullptr) return;
    r = new RegisterDialog(this);
    r->show();
}

void LogInDialog::on_logInBtn_clicked()
{
    QString name{ui->user_edit->text()};
    if (name.isEmpty() || ui->pass_edit->text().isEmpty()){
        showTip("请输入用户名和密码", false);
    }

    isGetAvatar(name);

    //发送http请求登录
    QJsonObject json_obj;
    json_obj["username"] = name;
    json_obj["password"] = ui->pass_edit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(GATE_URL+"/user/login"),
                                        QJsonDocument(json_obj).toJson(), ReqId::ID_LOGIN_USER,Modules::LOGINMOD);
}

void LogInDialog::slot_login_mod_finish(QByteArray data, ReqId id, ErrorCodes err)
{
    if (err != ErrorCodes::SUCCESS){
        showTip(data,false);
        return;
    }

    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);

    if (jsonError.error != QJsonParseError::NoError){
        qDebug() << "JSON解析错误：" << jsonError.errorString();
    }
    QJsonObject jsonObj{jsonDoc.object()};

    _handlers[id](jsonObj);
}

void LogInDialog::on_pushButton_clicked()
{
    parentWindow->close();
}

void LogInDialog::keyPressEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        on_logInBtn_clicked();
    }
    QWidget::keyPressEvent(event);
}

